package manage.model;

import m.common.model.FieldMeta;
import m.common.model.LinkTableMeta;
import m.common.model.Model;
import m.common.model.TableMeta;
import m.common.model.type.FieldType;
import m.common.model.util.ModelQueryList;
import m.common.model.util.QueryCondition;
import m.system.cache.CacheUtil;
import m.system.cache.FlushCacheList;
import m.system.util.ObjectUtil;

import java.util.ArrayList;
import java.util.List;

@TableMeta(name="os_admin_group_power",description="用户组权限表")
public class AdminGroupPower extends Model implements FlushCacheList {
	private static final long serialVersionUID = 1L;

	@FieldMeta(name="name",type=FieldType.STRING,length=50,description="名称")
	private String name;
	@LinkTableMeta(name="admin_group_oid",table=AdminGroup.class,description="管理员组")
	private AdminGroup adminGroup;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public AdminGroup getAdminGroup() {
		return adminGroup;
	}
	public void setAdminGroup(AdminGroup adminGroup) {
		this.adminGroup = adminGroup;
	}

	@Override
	public List<AdminGroupPower> getCacheList(String key) throws Exception {
		//key用逗号分开 1:adminOid 管理员 ,2:orgGroupOid 登录机构
		String[] arr=key.split(",");
		AdminLogin admin= CacheUtil.get(AdminLogin.class,arr[0]);
		OrgGroupView org=arr.length>1?CacheUtil.get(OrgGroupView.class,arr[1]):new OrgGroupView();
		List<QueryCondition> condList=new ArrayList<>();
		if(ObjectUtil.notEmptyOid(admin.getAdminGroup())){//管理员组 A
			condList.add(QueryCondition.eq("adminGroup.oid",admin.getAdminGroup().getOid()));
		}
		condList.add(//角色 B
			QueryCondition.in("adminGroup.oid",
				ModelQueryList.instance(AdminGroupLink.class,
					new String[] {"adminGroup.oid"}, null,
					QueryCondition.and(
						QueryCondition.eq("admin.oid", admin.getOid()),
						QueryCondition.eq("type", "B"),
						QueryCondition.or(
							QueryCondition.isEmpty("orgGroup.oid"),
							QueryCondition.eq("orgGroup.oid",org.getOid()),
							QueryCondition.eq("orgGroup.parent.oid",org.getOid())
						)
					)
				)
			)
		);
		if(ObjectUtil.notEmptyOid(org)){//机构部门 C
			condList.add(QueryCondition.eq("adminGroup.oid",org.getOid()));
			if(ObjectUtil.notEmptyOid(org.getDept())){
				condList.add(QueryCondition.eq("adminGroup.oid",org.getDept().getOid()));
			}
		}
		return ModelQueryList.getModelList(AdminGroupPower.class, new String[] {"*"}, null,
			QueryCondition.or(condList.toArray(new QueryCondition[0]))
		);
	}
}
